package com.banmoon.collection;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock
 * 1、创建公共Lock锁
 * 2、使用lock方法进行上锁
 * 3、在finally代码块中释放锁
 */
public class Demo4 {

    public static void main(String[] args) {
        TicketServer ticketServer = new TicketServer();
        new Thread(ticketServer, "A").start();
        new Thread(ticketServer, "B").start();
        new Thread(ticketServer, "C").start();
    }

}

class TicketServer implements Runnable{

    private int ticketNum = 10;

    // 创建锁
    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        while (true){
            // 上锁
            lock.lock();
            try {
                if(ticketNum<=0)
                    return;
                System.out.println(name + "：取到了第" + ticketNum + "张票");
                // 模拟网络延迟
                Thread.sleep(200);
                ticketNum--;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                // 最后始终都要释放锁
                lock.unlock();
            }
        }
    }

}